package com.ml.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ml.admin.converter.LoginConverter;
import com.ml.admin.converter.UserConverter;
import com.ml.admin.mapper.UserMapper;
import com.ml.admin.pojo.po.UserPO;
import com.ml.admin.pojo.vo.UserVO;
import com.ml.admin.service.UserService;
import com.ml.admin.utils.JwtUtil;
import com.ml.admin.utils.ResponseEnum;
import com.ml.admin.utils.ReturnResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;

/**
 * @author ml
 * @date 2023/3/9 10:50
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoginConverter loginConverter;
    //第一版简单设置
    @Value("${password.salt}")
    private String salt;
    /**
     * 编辑用户信息 todo 后续优化
     * @param vo vo
     * @return success or failure
     */
    @Override
    public ReturnResponse editUserInfo(UserVO vo) {
        UserPO po = loginConverter.voToPo(vo);
        String nickName = po.getNickName();
        String email = po.getEmail();
        String phone = po.getPhone();
        //重复校验
        if (StringUtils.isNotBlank(vo.getNickName())){
            UserPO checkNickName = userMapper.selectOne(new LambdaQueryWrapper<UserPO>()
                    .eq(UserPO::getNickName, nickName)
                    .ne(UserPO::getPhone,phone));
            if (!ObjectUtils.isEmpty(checkNickName)){
                return ReturnResponse.failure(ResponseEnum.NICKNAME_IS_EXSIT);
            }
        }


        if (StringUtils.isNotBlank(email)){
            UserPO checkEmail = userMapper.selectOne(new LambdaQueryWrapper<UserPO>()
                    .eq(UserPO::getEmail,email)
                    .ne(UserPO::getPhone, phone));
            if (!ObjectUtils.isEmpty(checkEmail)){
                return ReturnResponse.failure(ResponseEnum.EMAIL_IS_EXSIT);
            }
            //todo 后续加上邮箱验证？
        }
        int update = userMapper.update(null, new UpdateWrapper<UserPO>()
                .eq("phone", phone)
                .set("nick_name", nickName)
                .set("email", email));
        if (update<0){
            log.info("{}|编辑失败",phone);
            return ReturnResponse.failure();
        }else {
            log.info("{}|编辑成功",phone);
            return ReturnResponse.success();
        }
    }
    /**
     * 查询用户信息
     * @param phone 手机号
     * @return 用户信息
     */
    @Override
    public ReturnResponse queryUserInfo(String phone) {
        if (StringUtils.isBlank(phone)){
            return ReturnResponse.failure(ResponseEnum.PARAM_NOT_COMPLETE);
        }

        UserPO userInfo = userMapper.selectOne(new LambdaQueryWrapper<UserPO>()
                .eq(UserPO::getPhone, phone));
        if (ObjectUtils.isEmpty(userInfo)){
            return ReturnResponse.failure(ResponseEnum.USER_IS_NOT_EXSIT);
        }else {
            JSONObject userObject = new JSONObject();
            userObject.put("id",userInfo.getId());
            userObject.put("email",userInfo.getEmail());
            userObject.put("phone",userInfo.getPhone());
            userObject.put("nickName",userInfo.getNickName());
            return ReturnResponse.success(userObject);
        }
    }

    /**
     * 修改密码(设置密码)
     * @param vo 新密码
     * @return 成功 or 失败
     */
    @Override
    public ReturnResponse updatePwd(UserVO vo) {
        String passwordAgain = vo.getPasswordAgain();
        String password = vo.getPassword();
        String phone = vo.getPhone();
        if (StringUtils.isAnyBlank(password,passwordAgain,phone)){
            return ReturnResponse.failure(ResponseEnum.PARAM_NOT_COMPLETE);
        }
        //检查两次密码是否一致
        if (!password.equals(passwordAgain)){
            return ReturnResponse.failure(ResponseEnum.PASSWORD_IS_NOEQUELS);
        }
        //加密
        String newPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        int update = userMapper.update(null, new UpdateWrapper<UserPO>()
                .eq("phone", phone)
                .set("password", newPassword));
        if (update > 0){
            log.info("{}|设置（修改）密码成功",phone);
            return ReturnResponse.success();
        }else {
            log.info("{}|设置（修改）密码失败",phone);
            return ReturnResponse.failure();
        }
    }
}
